package site.anxuan.seckill.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import site.anxuan.seckill.common.ErrorCode;
import site.anxuan.seckill.common.Results;
import site.anxuan.seckill.entity.Result;
import site.anxuan.seckill.property.WebProperty;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@AllArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final WebProperty webProperty;

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getParameter("token");
        Boolean existUser = redisTemplate.hasKey("loginToken:" + token);
        if (!StringUtils.hasText(token) || existUser == null || !existUser) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setHeader("Access-Control-Allow-Origin", webProperty.getPath());
            response.setHeader("Access-Control-Allow-Credentials", "true");
            PrintWriter writer = response.getWriter();
            Map<Object, Object> data = new HashMap<>();
            data.put("code", ErrorCode.USER_NOT_LOGIN);
            data.put("message", "请先登录！");
            writer.write(JSONObject.toJSONString(Results.failure(data)));
            return false;
        }
        return true;
    }

}
